package com.cxj.musicplayer.audio;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.cxj.musicplayer.MainActivity;
import com.cxj.musicplayer.activity.OnPlaying;
import com.cxj.musicplayer.activity.SongsListActivity;
import com.cxj.musicplayer.data.DataManager;
import com.cxj.musicplayer.musicsource.network.DownloadFrom163;
import com.cxj.musicplayer.service.MediaService;

import java.io.File;
import java.io.IOException;

import static android.content.Context.BIND_AUTO_CREATE;

public class PlayerManager {
    private static PlayerManager playerManager;

    private MediaPlayer mediaPlayer;
    private static final String TAG = MainActivity.class.getSimpleName();
    private static MediaService.MusicController mMusicController;
    private Context mContext = null;


    private PlayerManager(Context context){
        mContext = context;
        mMusicController = (MediaService.MusicController)DataManager.concurrentHashMap_object_data.get("music_controller");
    }

    public static PlayerManager getPlayerManager(Context context){
        return new PlayerManager(context);
    }


    public void play_songs(final OnPlaying onPlaying, final String song_id, final int i, final String source) {
        Log.i(getClass().getName(), "play_songs");
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                String path = mContext.getApplicationContext().getFilesDir().getAbsolutePath() + "/songs/";
                File mp3 = new File(path + song_id + ".mp3");
                if (!mp3.exists()) {

                    Log.i("开始下载", song_id);
                    boolean b = DownloadFrom163.download(mContext, song_id);
                    if (!b) {
                        Message message = new Message();
                        message.what = onPlaying.DOWNLOAD_FAIL;

                        onPlaying.handle.sendMessage(message);
                        if (mp3.exists()) {
                            mp3.delete();
                        }
                        return;
                    }
                    System.out.println("下载完成");
                }
                try {
                    mMusicController.play(onPlaying, song_id, i, source);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void reload_song(OnPlaying onPlaying, final String song_id, final int i){
        mMusicController.restart(onPlaying);
    }

}
